<template>
  <view class="warehouse-container">
    <!-- A. 页面头部 -->
    <view class="page-header">
      <text class="page-title">粗丝作业</text>
    </view>

    <!-- B. 主信息区 -->
    <view class="plan-form-container">
      <view class="section-header">
        <text class="section-title">作业设定</text>
      </view>

      <view class="form-section">
        <view class="form-row">
          <view
            class="form-group"
            style="flex-direction: row; align-items: center"
          >
            <text
              class="form-label"
              style="margin-right: 20rpx; margin-bottom: 0"
              >生产工序</text
            >
            <picker
              mode="selector"
              :range="processOptions"
              range-key="text"
              :value="currentProcessIndex"
              @change="handleProcessChange"
              class="form-picker"
              style="flex: 1"
            >
              <view class="picker-content">
                <text>{{
                  currentProcess && currentProcess.processName
                    ? currentProcess.processName
                    : "请选择生产工序"
                }}</text>
                <text class="picker-arrow">▼</text>
              </view>
            </picker>
          </view>
        </view>

        <view class="form-row">
          <view
            class="form-group"
            style="flex-direction: row; align-items: baseline; flex: 1"
          >
            <text class="form-label" style="margin-right: 10px">班别：</text>
            <text class="form-value">{{ workClass || "未设置" }}</text>
          </view>
          <view
            class="form-group"
            style="
              flex-direction: row;
              align-items: baseline;
              flex: 1;
              margin-left: 20px;
            "
          >
            <text class="form-label" style="margin-right: 10px">班次：</text>
            <text class="form-value">{{ workShift || "未设置" }}</text>
          </view>
        </view>

        <view class="form-row">
          <view
            class="form-group"
            style="flex-direction: row; align-items: center; flex: 1"
          >
            <text
              class="form-label"
              style="margin-right: 20rpx; margin-bottom: 0"
              >机组</text
            >
            <view class="form-picker" style="flex: 1; position: relative">
              <input
                type="text"
                class="form-input"
                placeholder="请输入机组编码（支持扫码）"
                v-model.trim="formData.prodCenterNo"
                style="width: 100%"
              />
              <text
                class="picker-arrow"
                style="
                  position: absolute;
                  right: 10px;
                  top: 50%;
                  transform: translateY(-50%);
                "
                >📷</text
              >
            </view>
          </view>
        </view>

        <view class="form-row">
          <view class="form-group" style="flex: none; width: 100%">
            <text class="form-label">操作备注</text>
            <input
              type="text"
              class="form-input"
              placeholder="请输入操作备注"
              style="
                border: 1px solid #e0e0e0;
                border-radius: 6px;
                padding: 8px;
                background-color: #fafafa;
                resize: vertical;
                min-height: 60px;
                font-size: 14px;
                line-height: 1.4;
              "
              v-model.trim="formData.busMemo"
            />
          </view>
        </view>
      </view>
    </view>

    <!-- C. 投料作业区域 -->
    <view class="plan-form-container">
      <view class="section-header">
        <text class="section-title">投料作业</text>
      </view>

      <view class="form-section">
        <view class="form-row">
          <view class="form-group" style="flex: none; width: 100%">
            <!-- 使用统一扫码输入组件 -->
            <ScanInput
              v-model="searchForm.searchCode"
              placeholder="1.请扫码批次号/机组/计量秤"
              tip-text="支持扫描批次号"
              :loading="false"
              :on-scan-result="handleScanResult"
              :on-confirm="handleScanConfirm"
              ref="scanInputRef"
            />
          </view>
        </view>

        <!-- 炉次信息表格 -->
        <view class="table-container">
          <view class="table-body">
            <view class="table-row header">
              <text class="table-cell">选择</text>
              <text class="table-cell">炉次号</text>
              <text class="table-cell">批次号</text>
              <text class="table-cell">工序编码</text>
              <text class="table-cell">工序名称</text>
              <text class="table-cell">钢种</text>
              <text class="table-cell">规格</text>
              <text class="table-cell">重量</text>
              <text class="table-cell">数量</text>
              <text class="table-cell">生产日期</text>
            </view>
            <view
              class="table-row"
              v-for="(item, index) in furnaceTable"
              :key="index"
              @tap="toggleRowSelection(index)"
            >
              <view class="table-cell">
                <view
                  class="custom-checkbox"
                  :class="{ checked: item.selected }"
                  @tap.stop="toggleRowSelection(index)"
                >
                </view>
              </view>
              <text class="table-cell">{{ item.furnaceNo }}</text>
              <text class="table-cell">{{ item.batchNo || "-" }}</text>
              <text class="table-cell">{{ item.processNo || "-" }}</text>
              <text class="table-cell">{{ item.processName || "-" }}</text>
              <text class="table-cell">{{ item.steelGradeName }}</text>
              <text class="table-cell">{{ item.prodSpec || "-" }}</text>
              <text class="table-cell">{{ item.scrapWg || "0" }}</text>
              <text class="table-cell">{{ item.scrapCount || "0" }}</text>
              <text class="table-cell">{{
                dateHelperApi.formatDate(item.inDate)
              }}</text>
            </view>
          </view>
        </view>
      </view>
    </view>
    <view class="plan-form-container">
      <view class="form-section">
        <view class="form-row">
          <view class="form-group" style="flex: none; width: 100%">
            <text class="form-label">批次操作</text>
            <view style="display: flex; align-items: center; gap: 8px">
              <input
                type="text"
                class="form-input"
                placeholder="请点击批次打印自动生成"
                v-model.trim="formData.batchNo"
                style="flex: 1"
              />
            </view>
            <view class="form-row">
              <button class="btn-submit" @click="handlePrintBatch">
                2.打印
              </button>
              <button class="btn-submit" @click="handleCreateBatch">
                拆批
              </button>
              <!-- <button class="btn-submit" @click="handleBatchQuery">
                记录查询
              </button> -->
            </view>
          </view>
        </view>
      </view>
    </view>
    <!-- D. 产出作业区域 -->
    <view class="plan-form-container">
      <view class="section-header">
        <text class="section-title">产出作业</text>
      </view>

      <!-- TAB页切换 -->
      <view class="tab-container">
        <view
          class="tab-item"
          :class="{ active: activeTab === 'plan' }"
          @click="activeTab = 'plan'"
        >
          3.计划设定
        </view>
        <view
          class="tab-item"
          :class="{ active: activeTab === 'product' }"
          @click="activeTab = 'product'"
        >
          4.产品下线
        </view>
      </view>
      <!-- 计划设定TAB内容 -->
      <view v-if="activeTab === 'plan'" class="tab-content">
        <view class="section-header">
          <text class="section-title">查询条件</text>
          <view class="time-filter-buttons">
            <button
              class="filter-btn"
              :class="{ active: planQueryData.dateType === 'today' }"
              @tap="changeDateFilter('today')"
            >
              今日
            </button>
            <button
              class="filter-btn"
              :class="{ active: planQueryData.dateType === 'yesterday' }"
              @tap="changeDateFilter('yesterday')"
            >
              昨日
            </button>
            <button
              class="filter-btn"
              :class="{ active: planQueryData.dateType === 'tomorrow' }"
              @tap="changeDateFilter('tomorrow')"
            >
              明日
            </button>
            <button
              class="filter-btn"
              :class="{ active: planQueryData.dateType === 'week' }"
              @tap="changeDateFilter('week')"
            >
              近7天
            </button>
          </view>
        </view>

        <view class="section-header">
          <text class="section-title">汇总统计</text>
          <view class="statistics-info">
            <text class="stat-item">总计划量: {{ totalPlanWeight }} KG</text>
          </view>
        </view>
        <view
          style="
            display: flex;
            align-items: center;
            justify-content: space-between;
            margin-top: 8rpx;
          "
        >
          <text
            class="section-subtitle"
            style="
              font-size: 20rpx;
              color: #999;
              text-align: center;
              width: 100%;
              display: block;
            "
            >每次最多查询100条数据，更多请滑动底部加载</text
          >
        </view>
        <scroll-view class="table-scroll" scroll-y scroll-x>
          <view class="table-scroll-container">
            <view class="table-scroll-wrapper">
              <view class="table-content">
                <view class="table-row header">
                  <text class="table-cell">计划日期</text>
                  <text class="table-cell">钢种</text>
                  <text class="table-cell">规格</text>
                  <text class="table-cell">计划重量</text>
                  <text class="table-cell">操作</text>
                </view>
                <view
                  v-for="(plan, index) in planQueryData.planList"
                  :key="index"
                  class="table-row"
                  :class="{ selected: planQueryData.selectedPlan === plan }"
                  @click="selectPlan(plan)"
                >
                  <!-- <text class="table-cell" :title="plan.planNo">{{
                    plan.planNo
                  }}</text> -->
                  <text class="table-cell" :title="plan.reserveVarchar3">{{
                    plan.reserveVarchar3
                  }}</text>
                  <text class="table-cell" :title="plan.steelGradeName">{{
                    plan.steelGradeName
                  }}</text>
                  <text class="table-cell" :title="plan.prodSpec">{{
                    plan.prodSpec
                  }}</text>
                  <text class="table-cell">{{ plan.planCount }}</text>
                  <view class="table-cell">
                    <button class="btn-select" @click.stop="selectPlan(plan)">
                      选择
                    </button>
                  </view>
                </view>
              </view>
            </view>
          </view>
        </scroll-view>
      </view>
      <!-- 产品下线TAB -->
    </view>
    <view v-if="activeTab === 'product'" class="tab-content">
      <!-- 产出作业表单区 -->
      <view class="plan-form-container">
        <view class="section-header">
          <text class="section-title">产出数据</text>
        </view>

        <view class="form-section">
          <view class="form-row">
            <view class="form-group">
              <text class="form-label required">投料量(KG)</text>
              <input
                type="digit"
                class="form-input"
                placeholder="请输入投料量"
                v-model.number="formData.costWg"
                @blur="validateNumber($event, formData, 'costWg')"
              />
            </view>
            <!-- <view class="form-group">
              <text class="form-label">投料支数</text>
              <input
                type="number"
                class="form-input"
                placeholder="请输入投料支数"
                v-model.number="formData.costCount"
                @blur="validateNumber($event, formData, 'costCount')"
              />
            </view> -->
            <view class="form-group" style="flex: 1; margin-right: 10px">
              <text class="form-label required">产出量(KG)</text>
              <view style="display: flex; align-items: center; gap: 8px">
                <input
                  type="digit"
                  class="form-input"
                  placeholder="请扫码获取产出量"
                  v-model.number="formData.qaWg"
                  @blur="validateNumber($event, formData, 'qaWg')"
                  style="flex: 1"
                />
              </view>
            </view>
          </view>

          <!-- <view class="form-row">
            
            <view class="form-group">
              <text class="form-label">数量</text>
              <input
                type="number"
                class="form-input"
                placeholder="请输入产出支数"
                v-model.number="formData.qaCount"
                @blur="validateNumber($event, formData, 'qaCount')"
              />
            </view>
          </view> -->

          <view class="form-row">
            <view class="form-group">
              <text class="form-label">规格</text>
              <input
                type="text"
                class="form-input"
                placeholder="请输入规格"
                v-model.trim="formData.prodSpec"
              />
            </view>
            <view class="form-group">
              <!-- 占位，使规格输入框宽度与投料量输入框一致 -->
              <view class="form-group">
                <text class="form-label">废品重量(KG)</text>
                <input
                  type="digit"
                  class="form-input"
                  placeholder="请输入废品重量"
                  v-model.number="formData.scrapWg"
                  @blur="validateNumber($event, formData, 'scrapWg')"
                />
              </view>
            </view>
          </view>

          <!-- <view class="form-row"> -->
          <!-- <view class="form-group">
              <text class="form-label">废品支数</text>
              <input
                type="number"
                class="form-input"
                placeholder="请输入废品支数"
                v-model.number="formData.scrapCount"
                @blur="validateNumber($event, formData, 'scrapCount')"
              />
            </view> -->

          <!-- </view> -->

          <view class="form-row">
            <view class="form-group" style="flex: none; width: 100%">
              <text class="form-label">废品原因</text>
              <input
                type="text"
                class="form-input"
                placeholder="请输入废品原因"
                style="
                  border: 1px solid #e0e0e0;
                  border-radius: 6px;
                  padding: 8px;
                  background-color: #fafafa;
                  resize: vertical;
                  min-height: 60px;
                  font-size: 14px;
                  line-height: 1.4;
                "
                v-model.trim="formData.scrapReason"
              />
            </view>
          </view>
        </view>
      </view>
    </view>
    <!-- D. 按钮操作区 -->
    <view class="button-row">
      <button class="btn-reset" @click="handleReset">重置</button>
      <button class="btn-submit" @click="handleOffline">5.下线/修改</button>
    </view>
  </view>
</template>

<script>
// 导入API方法
import { getProcessOptions } from "@/api/md/process";
import { LzProdStockRealApi } from "@/api/warehouse/lzprodstockreal/index.js";
import { PlanLzApi } from "@/api/pp/planlz/index.js";
import { TcRecordApi } from "@/api/lz/tcrecord.js";
import { CsRecordApi } from "@/api/bs/csrecord/index.js";
import { warehouseApi } from "@/api/warehouse/warehouse";
// 导入统一扫码输入组件
import ScanInput from "@/components/ScanInput";

import { dateHelperApi } from "@/pages/smart/warehouse/utils/date-helper";
import { pdaScanApi } from "@/pages/smart/pdaScan.js";
import { getDasKey } from "@/pages/smart/utils/das.js";
export default {
  name: "StockIn",
  // 混入PDA扫码和打印功能
  mixins: [pdaScanApi],
  components: {
    ScanInput,
  },
  data() {
    return {
      // 表单数据
      formData: {
        currentDate: dateHelperApi.getCurrentDate(),
        processCode: "",
        processName: "",
        prodCenterNo: "", // 机组编码
        // 基础字段
        furnaceNo: "", // 炉次号（只保留第一个炉次号）
        reserveVarchar1: "", // 保留所有炉次号（多个炉次用分号隔开）
        operationMemo: "", // 操作备注
        // 增加物料编码和物料名称字段
        materialCode: "", // 物料编码
        materialName: "", // 物料名称
        planNo: "", // 计划明细编号
        // 投料作业字段
        costWg: "", // 钢棒重量
        costCount: "", // 钢棒支数
        // 产出作业字段
        batchNo: "", // 批次号
        lastBatchNo: "", // 上级批号（拆批前的批号）
        prodSpec: "", // 规格
        qaWg: "", // 产出量
        qaCount: "", // 产出支数
        scrapCount: "", // 废品支数
        scrapWg: "", // 废品重量
        scrapReason: "", // 废品原因
      },
      // 扫码查询表单
      searchForm: {
        searchCode: "", // 扫码内容
      },
      // TAB页管理
      activeTab: "plan", // 当前激活的TAB页: plan, product
      // 计划查询数据
      planQueryData: {
        dateType: "today", // 日期类型: today, yesterday, tomorrow, week
        planList: [], // 计划列表
        selectedPlan: null, // 选中的计划
        pageNum: 1, // 当前页码
        pageSize: 100, // 每页条数
        loading: false, // 加载状态
        hasMore: true, // 是否还有更多数据
        planCount: 0, // 计划总数（使用实际的planCount字段）
      },

      // 当前工序信息
      currentProcess: {
        processCode: "",
        processName: "请选择生产工序",
      },
      // 班次班组信息
      workShift: "", // 班次
      workClass: "", // 班组

      // 工序选项列表
      processOptions: [],
      // 当前工序索引
      currentProcessIndex: -1,
      // 炉次信息表格数据
      furnaceTable: [],
      // 炉次号显示（用于产品下线Tab）
      furnaceNoDisplay: "",
      // 修改模式相关属性
      isEditMode: false, // 是否处于修改模式
      editRecordId: null, // 当前修改的记录ID
      // 渣系选项
      slagSystemOptions: [], // 渣系下拉选项
    };
  },
  computed: {
    // 日期工具命名空间（供模板使用）
    dateHelperApi() {
      return dateHelperApi;
    },
    // 总计划重量计算
    totalPlanWeight() {
      if (
        !this.planQueryData.planList ||
        this.planQueryData.planList.length === 0
      ) {
        return 0;
      }
      return this.planQueryData.planList.reduce((total, plan) => {
        const weight = parseFloat(
          plan.planCount.toString().replace(/[^\d.]/g, "")
        );
        return total + (isNaN(weight) ? 0 : weight);
      }, 0);
    },
  },
  async onLoad(options) {
    await this.loadProcessOptions(); // 加载工序选项
    this.loadCurrentProcess(); // 加载当前工序
    // 初始化PDA打印模块（来自mixin）
    this.initScanModule();

    // 页面加载时默认查询今日的计划
    await this.loadPlanList();

    // 如果有传入的recordId，进入修改模式
    if (options && options.recordId) {
      await this.loadRecordData(options.recordId);
    }
  },
  beforeDestroy() {
    // 停止PDA扫码，释放资源（来自mixin）
    this.stopPdaScan();
  },
  methods: {
    // 日期筛选切换
    changeDateFilter(dateType) {
      this.planQueryData.dateType = dateType;
      this.loadPlanList();
    },

    // 加载计划列表
    async loadPlanList(loadMore = false) {
      try {
        if (!loadMore) {
          this.planQueryData.pageNum = 1;
          this.planQueryData.hasMore = true;
        }

        this.planQueryData.loading = true;

        // 根据日期类型获取时间范围
        let timeRange = {};

        // 使用通用的updateDateRange函数获取时间范围
        const result = dateHelperApi.updateDateRange(
          this.planQueryData.dateType,
          {
            callback: ({ startDate, endDate }) => {
              timeRange = { startDate, endDate };
            },
          }
        );

        // 调用计划查询接口
        const params = {
          pageNum: this.planQueryData.pageNum,
          pageSize: this.planQueryData.pageSize,
          reserveVarchar2: this.currentProcess?.processName || "",
        };

        // 增加当前工序查询参数
        if (this.currentProcess && this.currentProcess.processCode) {
          params.processCode = this.currentProcess.processCode;
        }

        //只有在时间范围有效时才添加时间参数 - 使用数组格式传递到reserveVarchar3字段
        if (timeRange.startDate && timeRange.endDate) {
          // dateHelperApi.updateDateRange返回的是YYYY-MM-DD HH:mm:ss格式
          // 格式化为YYYY-MM-DD格式，去掉时分秒
          const startDateFormatted = timeRange.startDate.split(" ")[0];
          const endDateFormatted = timeRange.endDate.split(" ")[0];
          params.reserveVarchar3 = [startDateFormatted, endDateFormatted];
        }
        // if (timeRange.startDate && timeRange.endDate) {
        //   params.createDate = [timeRange.startDate, timeRange.endDate];
        // }

        const response = await PlanLzApi.getPlanLzDetailPage(params);

        if (response.code === 0 && response.data && response.data.list) {
          // 将查询结果转换为计划列表格式
          const newPlans = response.data.list.map((item) => ({
            planNo: item.planDetailNo,
            steelGradeName: item.steelGradeName || "",
            prodSpec: item.prodSpec || "",
            planCount: item.planCount ? `${item.planCount}KG` : "0KG",
            createTime: item.createTime || item.createDate || "",
            // 增加物料编码和物料名称字段
            materialCode: item.materialCode || "",
            materialName: item.materialName || "",
            // 使用实际的计划数量字段
            planCount: item.planCount || 0,
            reserveVarchar3: item.reserveVarchar3 || "",
          }));
          //赋值到planQueryData.planList
          if (loadMore) {
            this.planQueryData.planList.push(...newPlans);
          } else {
            this.planQueryData.planList = newPlans;
          }
          // 计算总计划数量 - 使用planCount字段而不是简单的列表长度
          this.planQueryData.planCount = this.planQueryData.planList.reduce(
            (total, plan) => {
              return total + (plan.planCount || 0);
            },
            0
          );

          // 检查是否还有更多数据
          if (newPlans.length < this.planQueryData.pageSize) {
            this.planQueryData.hasMore = false;
          }

          if (this.planQueryData.planList.length === 0) {
            uni.showToast({
              title: "未查询到计划信息",
              icon: "none",
            });
          } else if (!loadMore) {
            uni.showToast({
              title: `查询到${this.planQueryData.planList.length}条计划信息`,
              icon: "success",
            });
          }
        } else {
          this.planQueryData.planList = [];
          this.planQueryData.hasMore = false;
          uni.showToast({
            title: "查询计划信息失败",
            icon: "none",
          });
        }
      } catch (error) {
        console.error("查询计划信息失败:", error);
        this.planQueryData.planList = [];
        this.planQueryData.hasMore = false;
        uni.showToast({
          title: "查询计划信息失败",
          icon: "none",
        });
      } finally {
        this.planQueryData.loading = false;
      }
    },

    // 选择计划
    selectPlan(plan) {
      this.planQueryData.selectedPlan = plan;
      // 移除钢种规格赋值
      // this.form.steelGrade = plan.steelGradeName
      // this.form.prodSpec = plan.prodSpec

      // 添加新的字段赋值 - 使用formData instead of form
      this.formData.materialCode = plan.materialCode;
      this.formData.materialName = plan.materialName;
      this.formData.planNo = plan.planNo; // 将计划明细编号赋值给planNo
      this.formData.prodSpec = plan.prodSpec || ""; // 将计划的规格赋值给prodSpec

      this.formData.planId = plan.Id;
      this.formData.planCount = plan.planCount;
      console.log("计划明细编号formData:", this.formData);

      // 切换到产品下线TAB
      this.activeTab = "product";

      uni.showToast({
        title: "已选择计划",
        icon: "success",
      });
    },

    // 扫码结果处理
    handleScanResult(result) {
      // 预处理扫码结果
      if (result && result.length > 0) {
        this.searchForm.searchCode = result;
        this.handleScanConfirm();
      }
    },
    //加工中心扫码赋值
    handleAssignProdCenter(searchCode) {
      this.formData.prodCenterNo = searchCode;
      uni.showToast({
        title: `已获取机组信息: ${searchCode}`,
        icon: "success",
        duration: 2000,
      });
    },

    // 扫码确认查询 批次查询
    async handleScanConfirm() {
      if (!this.searchForm.searchCode.trim()) {
        uni.showToast({
          title: "请输入批次号",
          icon: "none",
        });
        return;
      }

      // 根据扫码内容判断查询类型并调用相应接口
      const searchCode = this.searchForm.searchCode.trim();
      //如果扫内容以DAS开头，则调用数采接口
      if (searchCode.startsWith("DAS")) {
        this.handleMeasureWeight(searchCode);
        return;
      }
      //如果扫内容以BS、LZ开头，则调用prodCenter赋值方法
      if (searchCode.startsWith("BS") || searchCode.startsWith("LZ")) {
        this.handleAssignProdCenter(searchCode);
        return;
      }

      try {
        // 调用炉次号查询接口
        const params = {
          batchNo: searchCode,
          pageNum: 1,
          pageSize: 10,
        };

        const response = await LzProdStockRealApi.getLzProdStockRealPage(
          params
        );

        if (response.code === 0 && response.data && response.data.list) {
          // 将查询结果转换为furnaceTable格式
          // 判断是否通过批次号查询：如果返回的数据中有记录的batchNo等于查询值，说明是通过批次号查询
          const hasBatchNoMatch = response.data.list.some(
            (item) => item.batchNo && item.batchNo === searchCode
          );

          let newData = response.data.list
            .filter((item) => {
              // 如果通过批次号查询，显示该批次下的所有数据
              if (hasBatchNoMatch) {
                return item.batchNo === searchCode;
              }
              // 如果通过炉次号查询，只显示未分配批次的数据
              return (
                !item.batchNo || item.batchNo === "" || item.batchNo === null
              );
            })
            .map((item) => ({
              furnaceNo: item.furnaceNo,
              batchNo: item.batchNo,
              processNo: item.processNo || "",
              processName: item.processName || "",
              steelGradeName: item.steelGradeName,
              prodSpec: item.prodSpec || "",
              scrapCount: item.scrapCount || 0,
              scrapWg: item.scrapWg || 0,
              inDate: item.inDate || dateHelperApi.getCurrentDate(),
              selected: false, // 初始化选择状态
            }));

          if (newData.length === 0) {
            this.furnaceTable = [];
            uni.showToast({
              title: "未查询到批次号信息",
              icon: "none",
            });
          } else {
            // 直接替换表格数据，不再追加
            this.furnaceTable = newData;

            // 如果查询结果只有一行，默认选中该行
            if (newData.length === 1) {
              newData[0].selected = true;
            }

            // 如果是批次号查询且有数据，进行自动赋值
            if (hasBatchNoMatch && newData.length > 0) {
              // 1. 将批次号赋值给【批次操作】的输入框
              this.formData.batchNo = searchCode;

              // 2. 计算批次对应的炉次信息中的重量总和，赋值给【产出作业】的投料量
              const totalWeight = newData.reduce((sum, item) => {
                return sum + (parseFloat(item.scrapWg) || 0);
              }, 0);
              this.formData.costWg = totalWeight > 0 ? totalWeight : "";

              // 3. 计算批次对应的炉次信息中的数量总和，赋值给【产出作业】的投料支数
              const totalCount = newData.reduce((sum, item) => {
                return sum + (parseInt(item.scrapCount) || 0);
              }, 0);
              this.formData.costCount = totalCount > 0 ? totalCount : "";
            }

            uni.showToast({
              title: `查询到${newData.length}条批次信息`,
              icon: "success",
            });
            // busMemo
            if (this.furnaceTable.length > 0) {
              // 重新生成busMemo，避免重复拼接
              const furnaceNos = this.furnaceTable.map(
                (item) => item.furnaceNo
              );
              this.formData.busMemo = furnaceNos.join(";");

              this.furnaceNoDisplay = this.furnaceTable[0].furnaceNo;
              // 表单中的钢种来自炉次号查询的第一行数据
              this.formData.steelGradeName =
                this.furnaceTable[0].steelGradeName || "";
              this.formData.prodSpec = this.furnaceTable[0].prodSpec || "";

              // 从炉次信息中获取炉号（批次对应的炉号）
              this.formData.furnaceNo = this.furnaceTable[0].furnaceNo;
            }
          }
        } else {
          this.furnaceTable = [];
          this.furnaceNoDisplay = "";
          uni.showToast({
            title: "查询炉次号信息失败",
            icon: "none",
          });
        }
      } catch (error) {
        console.error("查询炉次号信息失败:", error);
        this.furnaceTable = [];
        this.furnaceNoDisplay = "";
        uni.showToast({
          title: "查询炉次号信息失败",
          icon: "none",
        });
      }

      // 如果furnaceTable有数据，使用第一个炉次的furnaceNo；否则使用searchCode（炉次号查询的情况）
      if (this.furnaceTable.length > 0) {
        this.formData.furnaceNo = this.furnaceTable[0].furnaceNo;
      } else {
        this.formData.furnaceNo = searchCode;
      }
    },

    /* 加载当前工序 */
    loadCurrentProcess() {
      // 尝试从用户配置中加载缓存的工序信息
      const userData = this.$store.state.user;
      const userConfig = userData.userConfig || {};
      if (userData && userData.userConfig) {
        const userConfig = userData.userConfig;
        // 从缓存中加载工序信息
        if (userConfig.processNo && userConfig.processName) {
          this.currentProcess = {
            processCode: userConfig.processNo,
            processName: userConfig.processName,
          };
          this.formData.processCode = userConfig.processNo;
          this.formData.processName = userConfig.processName;
          // 同步更新 reserveVarchar2 为当前生产工序名称
          this.formData.reserveVarchar2 = userConfig.processName;

          // 加载班次班组信息
          this.workShift = userConfig.workShift || "";
          this.workClass = userConfig.workClass || "";

          // 在工序选项中找到对应的索引
          const processIndex = this.processOptions.findIndex(
            (item) => item.value === userConfig.processNo
          );
          if (processIndex !== -1) {
            this.currentProcessIndex = processIndex;
          }
          return;
        }
      }

      // 如果没有缓存或缓存无效，默认选择第一个工序
      if (this.processOptions.length > 0) {
        this.currentProcess = {
          processCode: this.processOptions[0].value,
          processName: this.processOptions[0].text,
        };
        this.formData.processCode = this.currentProcess.processCode;
        this.formData.processName = this.currentProcess.processName;
        // 同步更新 reserveVarchar2 为当前生产工序名称
        this.formData.reserveVarchar2 = this.processOptions[0].text;
        this.currentProcessIndex = 0;
      }
    },

    // 加载工序选项
    async loadProcessOptions() {
      try {
        const options = await getProcessOptions();
        this.processOptions = options;
        console.log("生产工序选项加载成功:", this.processOptions);
      } catch (error) {
        // 静默处理错误
        console.error("加载工序选项失败:", error);
        this.processOptions = [];
      }
    },

    /* 处理工序选择变化 */
    handleProcessChange(e) {
      const index = e.detail.value;
      this.currentProcessIndex = index;
      const selectedProcess = this.processOptions[index];
      if (selectedProcess) {
        this.currentProcess = {
          processCode: selectedProcess.value,
          processName: selectedProcess.text,
        };
        this.formData.processCode = selectedProcess.value;
        this.formData.processName = selectedProcess.text;
        // 同步更新 reserveVarchar2 为当前生产工序名称
        this.formData.reserveVarchar2 = selectedProcess.text;
      }
    },

    // 拆批功能
    async handleCreateBatch() {
      // 校验批次操作中是否有批号
      if (!this.formData.batchNo || this.formData.batchNo.trim() === "") {
        uni.showToast({
          title: "没有批号无法进行拆批操作",
          icon: "none",
        });
        return;
      }

      // 校验是否存在炉次号（用于获取上道工序信息）
      if (!this.furnaceTable || this.furnaceTable.length === 0) {
        uni.showToast({
          title: "请先查询批次信息",
          icon: "none",
        });
        return;
      }

      // 调用拆批方法
      await this.doDepartBatch();
    },

    // 执行拆批操作
    async doDepartBatch() {
      try {
        // 获取上道工序信息（从投料作业中批次对应炉号的第一条记录获取）
        let feedProcessNo = "";
        let feedProcessName = "";
        if (this.furnaceTable.length > 0) {
          feedProcessNo = this.furnaceTable[0].processNo || "";
          feedProcessName = this.furnaceTable[0].processName || "";
        }

        // 准备拆批参数
        const departData = {
          // 当前工序信息
          processNo: this.currentProcess.processCode,
          processName: this.currentProcess.processName,
          // 上道工序信息（投料工序）
          feedProcessNo: feedProcessNo,
          feedProcessName: feedProcessName,
          // 当前批号
          batchNo: this.formData.batchNo,
          // 钢种信息
          steelGradeCode: this.formData.steelGradeCode || "",
          steelGradeName: this.formData.steelGradeName || "",
        };

        console.log("拆批参数:", departData);

        // 调用拆批API
        const response = await CsRecordApi.departBatch(departData);

        if (response.code === 0) {
          // 从响应中获取新批号
          if (response.data && response.data.newBatchNo) {
            // 保存上级批号（拆批前的批号）
            this.formData.lastBatchNo = this.formData.batchNo;
            // 更新为新批号
            this.formData.batchNo = response.data.newBatchNo;

            uni.showToast({
              title: `拆批成功，新批号：${response.data.newBatchNo}`,
              icon: "success",
              duration: 3000,
            });
          } else {
            uni.showToast({
              title: "拆批成功",
              icon: "success",
            });
          }
        } else {
          uni.showToast({
            title: response.msg || "拆批失败",
            icon: "none",
          });
        }
      } catch (error) {
        console.error("拆批失败:", error);
        uni.showToast({
          title: "拆批失败，请重试",
          icon: "none",
        });
      }
    },

    // 批次打印（调用提纯作业的打印逻辑）
    async handlePrintBatch() {
      if (!this.formData.batchNo) {
        uni.showToast({
          title: "请先创建批次",
          icon: "none",
        });
        return;
      }

      try {
        // 准备打印参数：批号、钢种、日期（年月日）
        const batchNo = this.formData.batchNo; // 批号
        const steelGrade = this.formData.steelGradeName || ""; // 钢种
        const date = dateHelperApi.getCurrentDate(); // 日期（年月日，格式：YYYY-MM-DD）

        // 调用PDA打印接口（与提纯作业保持一致）
        const printResult = this.pdaPrint(
          batchNo, // 批次号
          steelGrade + "/" + (this.formData.prodSpec || ""), // 规格（钢种/规格）
          date // 打印时间（年月日）
        );

        if (printResult) {
          uni.showToast({
            title: "批次打印成功",
            icon: "success",
          });
        } else {
          uni.showToast({
            title: "批次打印失败，请检查设备",
            icon: "none",
          });
        }
      } catch (error) {
        console.error("批次打印失败:", error);
        uni.showToast({
          title: "批次打印失败，请重试",
          icon: "none",
        });
      }
    },

    // 批量查询
    async handleBatchQuery() {
      try {
        // 显示加载中
        uni.showLoading({
          title: "查询中...",
        });

        // 调用批量查询API（这里使用现有的计划查询接口，可以根据需要调整参数）
        const params = {
          pageNum: 1,
          pageSize: 50, // 批量查询显示更多数据
          processName: "粗丝",
          batchNo: this.formData.batchNo,
          // 可以根据需要添加更多查询条件
        };

        const response = await CsRecordApi.getCsRecordPage(params);

        uni.hideLoading();

        if (response.code === 0) {
          // 将分页查询返回的第一行数据分别赋值给formData的字段中
          if (
            response.data &&
            response.data.list &&
            response.data.list.length > 0
          ) {
            const firstRow = response.data.list[0];

            // 细化为每个字段单独赋值，确保数据映射正确
            this.formData.furnaceNo = firstRow.furnaceNo;
            this.formData.batchNo = firstRow.batchNo;
            this.formData.steelGradeName = firstRow.steelGradeName;
            this.formData.steelGradeCode = firstRow.steelGradeCode;
            this.formData.prodSpec = firstRow.prodSpec;
            this.formData.standCode = firstRow.standCode;
            this.formData.standNo = firstRow.standNo;
            this.formData.materialCode = firstRow.materialCode;
            this.formData.materialName = firstRow.materialName;
            this.formData.planNo = firstRow.planNo;
            this.formData.slagSystem = firstRow.slagSystem;
            this.formData.slagRatio = firstRow.slagRatio;
            this.formData.workStaff = firstRow.workStaff;
            this.formData.busMemo = firstRow.busMemo;
            this.formData.reserveVarchar1 = firstRow.reserveVarchar1;
            this.formData.reserveVarchar2 = firstRow.reserveVarchar2;
            this.formData.reserveVarchar3 = firstRow.reserveVarchar3;
            this.formData.reserveVarchar4 = firstRow.reserveVarchar4;

            this.furnaceNoDisplay = firstRow.furnaceNo;
            // 数值类型字段需要特殊处理
            this.formData.qaWg = firstRow.qaWg;
            this.formData.qaCount = firstRow.qaCount;
            this.formData.scrapCount = firstRow.scrapCount;
            this.formData.scrapWg = firstRow.scrapWg;
            this.formData.costWg = firstRow.costWg;
            this.formData.costCount = firstRow.costCount;
            console.log("查询到的第一行数据formData:", this.formData);
            console.log("查询到的第一行数据firstRow:", firstRow);
            uni.showToast({
              title: `查询到${response.data.list.length}条记录`,
              icon: "success",
            });
          } else {
            uni.showToast({
              title: "未查询到相关记录",
              icon: "none",
            });
          }
        } else {
          uni.showToast({
            title: response.msg || "查询失败",
            icon: "none",
          });
        }
      } catch (error) {
        uni.hideLoading();
        console.error("批量查询失败:", error);
        uni.showToast({
          title: "查询失败，请重试",
          icon: "none",
        });
      }
    },

    // 表格滚动到底部加载更多

    // 数字验证（允许负数）
    validateNumber(event, obj, field) {
      const value = parseFloat(event.detail.value);
      if (isNaN(value)) {
        obj[field] = "";
        uni.showToast({
          title: "请输入有效的数字",
          icon: "none",
        });
      } else {
        obj[field] = value;
      }

      // // 增加逻辑：当炉次表的重量和数量输入值发生变化时候，form表单的中的投料量和钢棒支数统一更新
      // if (obj && this.furnaceTable.includes(obj)) {
      //   // 如果修改的是炉次表格中的数据
      //   if (field === "scrapWg" || field === "scrapCount") {
      //     this.updateFormFeedData();
      //   }
      // }
    },

    // 计量按钮处理
    async handleMeasureWeight() {
      try {
        // 校验当前工序是否存在
        if (!this.currentProcess || !this.currentProcess.processName) {
          uni.showToast({
            title: "请先选择生产工序",
            icon: "none",
          });
          return;
        }

        // 显示加载提示
        uni.showLoading({
          title: "计量中...",
        });

        // 调用getDasKey方法获取计量数据，获取扫码的值
        const parameterName = this.searchForm.searchCode;
        const result = await getDasKey(parameterName);
        console.log("数采result.result[0].v:", result.result[0].v);
        uni.hideLoading();

        // 处理返回的数据（可能的数据结构：result.data 或 result 本身）
        let weightValue = null;

        if (result) {
          weightValue = result.result[0].v || 0;
        }

        if (weightValue !== null && weightValue !== undefined) {
          // 将获取到的值填充到产出量输入框
          const parsedValue = parseFloat(weightValue);
          if (!isNaN(parsedValue)) {
            this.formData.qaWg = parsedValue;
            uni.showToast({
              title: `计量成功：${this.formData.qaWg}KG`,
              icon: "success",
            });
          } else {
            uni.showToast({
              title: "获取到的计量数据格式不正确",
              icon: "none",
            });
          }
        } else {
          uni.showToast({
            title: "未找到对应的数采配置或数据为空",
            icon: "none",
          });
        }
      } catch (error) {
        uni.hideLoading();
        console.error("计量失败:", error);
        uni.showToast({
          title: error.message || "计量失败，请检查数采配置",
          icon: "none",
        });
      }
    },

    // 切换行选择状态
    toggleRowSelection(index) {
      // 单选逻辑：点击某行时，先取消所有行的选择，然后选中当前行
      this.furnaceTable.forEach((item, i) => {
        item.selected = i === index ? !item.selected : false;
      });
    },

    // 重置表单
    handleReset() {
      // 重置所有表单数据到初始状态
      this.formData = {
        currentDate: dateHelperApi.getCurrentDate(),
        processCode: this.currentProcess.processCode,
        processName: this.currentProcess.processName,
        // 基础字段
        furnaceNo: "", // 炉次号（只保留第一个炉次号）
        reserveVarchar1: "", // 保留所有炉次号（多个炉次用分号隔开）
        operationMemo: "", // 操作备注
        workStaff: "", // 配渣工
        // 增加物料编码和物料名称字段
        materialCode: "", // 物料编码
        materialName: "", // 物料名称
        planDetailNo: "", // 计划明细编号
        // 投料作业字段
        costWg: "", // 钢棒重量
        costCount: "", // 钢棒支数
        // 产出作业字段
        batchNo: "", // 批次号
        lastBatchNo: "", // 上级批号（拆批前的批号）
        prodSpec: "", // 规格
        slagSystem: "", // 渣系
        slagRatio: "", // 渣系配比
        qaWg: "", // 钢锭重量
        qaCount: "", // 钢锭支数
        scrapCount: "", // 废品支数
        scrapWg: "", // 废品重量
        scrapReason: "", // 废品原因
      };

      // 重置其他状态
      this.searchForm.searchCode = "";
      this.activeTab = "plan";
      this.planQueryData.selectedPlan = null;
      this.furnaceTable = [];
      this.furnaceNoDisplay = "";
      // 重置表格编辑状态为可编辑
      this.isTableEditable = true;

      // 重新加载计划列表
      // this.loadPlanList();

      uni.showToast({
        title: "刷新成功",
        icon: "success",
      });
    },

    // 下线
    async handleOffline() {
      // 校验投料作业中是否选中了一行
      const selectedRows = this.furnaceTable.filter((item) => item.selected);
      if (selectedRows.length === 0) {
        uni.showToast({
          title: "请先在投料作业中选择一行数据",
          icon: "none",
        });
        return;
      }
      if (selectedRows.length > 1) {
        uni.showToast({
          title: "投料作业中只能选择一行数据进行下线操作",
          icon: "none",
        });
        return;
      }

      // 获取选中的行数据
      const selectedRow = selectedRows[0];

      // 校验是否存在批次号
      if (!this.formData.batchNo) {
        uni.showToast({
          title: "请先创建批次号",
          icon: "none",
        });
        return;
      }

      // 校验是否存在计划明细编号
      // if (!this.formData.planNo) {
      //   uni.showToast({
      //     title: "请先选择计划",
      //     icon: "none",
      //   });
      //   return;
      // }

      //投料重量校验
      if (!this.formData.costWg) {
        uni.showToast({
          title: "请先输入投料重量",
          icon: "none",
        });
        return;
      }

      // 校验是否存在钢锭重量
      if (!this.formData.qaWg || this.formData.qaWg === "") {
        uni.showToast({
          title: "请先输入钢锭重量",
          icon: "none",
        });
        return;
      }

      // 校验钢锭重量是否为有效数字
      const qaWg = parseFloat(this.formData.qaWg);
      if (isNaN(qaWg) || qaWg <= 0) {
        uni.showToast({
          title: "请输入有效的钢锭重量",
          icon: "none",
        });
        return;
      }

      // 校验钢锭支数是否为有效数字
      if (this.formData.qaCount && this.formData.qaCount !== "") {
        const qaCount = parseInt(this.formData.qaCount);
        if (isNaN(qaCount) || qaCount < 0) {
          uni.showToast({
            title: "请输入有效的钢锭支数",
            icon: "none",
          });
          return;
        }
      }

      uni.showModal({
        title: "确认下线",
        content: `确定要执行下线操作吗？\n本次投料量：${this.formData.costWg}KG\n本次下线量：${qaWg}KG`,
        success: async (res) => {
          if (res.confirm) {
            try {
              // 获取投料工序信息（从选中的行获取）
              const feedProcessNo = selectedRow.processNo || "";
              const feedProcessName = selectedRow.processName || "";

              // 准备下线参数（包含出库和入库信息）
              // 确定上级批号：如果有lastBatchNo则使用，否则使用当前batchNo
              // 如果当前批号包含"-"（说明是拆批后的批号），提取上级批号
              let lastBatchNo = this.formData.lastBatchNo || "";
              if (
                !lastBatchNo &&
                this.formData.batchNo &&
                this.formData.batchNo.includes("-")
              ) {
                // 从拆批后的批号中提取上级批号（去掉"-X"部分）
                const parts = this.formData.batchNo.split("-");
                if (parts.length >= 2) {
                  // 去掉最后一部分，重新组合
                  lastBatchNo = parts.slice(0, -1).join("-");
                }
              }
              // 如果还是没有上级批号，使用当前批号
              if (!lastBatchNo) {
                lastBatchNo = this.formData.batchNo;
              }

              const offlineData = {
                // 基本信息（使用选中行的数据）
                furnaceNo: selectedRow.furnaceNo, // 使用选中行的炉次号
                batchNo: this.formData.batchNo, // 当前批号（拆批后的批号）
                lastBatchNo: lastBatchNo, // 上级批号（拆批前的批号，用于出库查询）
                planNo: this.formData.planNo, // 计划明细编号
                processNo: this.currentProcess.processCode, // 当前工序（下线工序）
                processName: this.currentProcess.processName, // 当前工序名称（下线工序）
                prodCenterNo: this.formData.prodCenterNo || "", // 机组编码
                // 投料工序信息（使用选中行的工序信息）
                feedProcessNo: feedProcessNo, // 投料工序编码（来自选中行）
                feedProcessName: feedProcessName, // 投料工序名称（来自选中行）
                // 日期格式转换为时间戳（毫秒）
                ywDate: this.formData.currentDate
                  ? new Date(this.formData.currentDate + "T00:00:00").getTime()
                  : new Date().setHours(0, 0, 0, 0),
                workShift: this.workShift,
                wortkType: this.workClass,
                workStaff: this.formData.workStaff || "",
                busMemo: this.formData.busMemo || "",

                // 钢种和规格信息（使用选中行的数据）
                steelGradeName: selectedRow.steelGradeName || "",
                steelGradeCode: this.formData.steelGradeCode || "",
                prodSpec: selectedRow.prodSpec || this.formData.prodSpec || "",
                standCode: this.formData.standCode || "",
                standNo: this.formData.standNo || "",

                // 物料编码和物料名称
                materialCode: this.formData.materialCode || "",
                materialName: this.formData.materialName || "",

                // 投料信息（用于出库，使用前端【产出数据】中的投料量和投料支数）
                qmAmount: this.formData.costWg
                  ? parseFloat(this.formData.costWg)
                  : null, // 使用前端【产出数据】中的投料量
                costCount: this.formData.costCount
                  ? parseFloat(this.formData.costCount)
                  : null, // 使用前端【产出数据】中的投料支数

                // 产出信息（用于入库）
                qaWg: this.formData.qaWg
                  ? parseFloat(this.formData.qaWg)
                  : null, // 产出重量（用于入库）
                qaCount: this.formData.qaCount
                  ? parseFloat(this.formData.qaCount)
                  : null, // 产出支数（用于入库）

                // 废品信息
                scrapWg: this.formData.scrapWg
                  ? parseFloat(this.formData.scrapWg)
                  : null,
                scrapCount: this.formData.scrapCount
                  ? parseFloat(this.formData.scrapCount)
                  : null,
                scrapReason: this.formData.scrapReason || "",

                // 预留字段
                reserveVarchar1: this.formData.reserveVarchar1 || "",
                reserveVarchar2: this.formData.reserveVarchar2 || "",
                reserveVarchar3: this.formData.reserveVarchar3 || "",
                reserveVarchar4: this.formData.reserveVarchar4 || "",
              };

              console.log("生产下线参数（包含出库和入库）:", offlineData);

              // 调用粗丝下线API（先出库后入库，在一个事务中执行）
              const response = await CsRecordApi.offlineCsRecordWithOnline(
                offlineData
              );

              if (response.code === 0) {
                uni.showToast({
                  title: `下线成功，投料${this.formData.costWg}KG，下线${qaWg}KG`,
                  icon: "success",
                  duration: 3000,
                });

                // 刷新表单和炉次列表 （包括计划明细）
                // 清空表单，清空投料的炉次查询
                this.refreshAfterOffline();
              } else {
                uni.showToast({
                  title: response.msg || "下线失败",
                  icon: "none",
                });
              }
            } catch (error) {
              console.error("下线处理失败:", error);
              uni.showToast({
                title: "下线处理失败，请重试",
                icon: "none",
              });
            }
          }
        },
      });
    },

    // 加载记录数据（用于修改模式）
    async loadRecordData(recordId) {
      try {
        uni.showLoading({
          title: "加载数据中...",
        });

        const response = await CsRecordApi.getCsRecord(recordId);

        if (response.code === 0 && response.data) {
          const record = response.data;

          // 设置编辑模式
          this.isEditMode = true;
          this.editRecordId = recordId;

          // 填充表单数据
          this.formData = {
            ...this.formData,
            // 基本信息
            furnaceNo: record.furnaceNo || "",
            reserveVarchar1: record.reserveVarchar1 || "",
            batchNo: record.batchNo || "",
            batchNoSerial: record.batchNoSerial || "",
            currentDate: record.ywDate || "",
            workStaff: record.workStaff || "",
            busMemo: record.busMemo || "",

            // 钢种和规格信息
            steelGradeName: record.steelGradeName || "",
            steelGradeCode: record.steelGradeCode || "",
            prodSpec: record.prodSpec || "",
            standCode: record.standCode || "",
            standNo: record.standNo || "",
            materialCode: record.materialCode || "",
            materialName: record.materialName || "",
            planDetailNo: record.planDetailNo || "",

            // 产出信息
            qaWg: record.qaWg ? record.qaWg.toString() : "",
            qaCount: record.qaCount ? record.qaCount.toString() : "",

            // 废品信息
            scrapCount: record.scrapCount ? record.scrapCount.toString() : "",
            scrapWg: record.scrapWg ? record.scrapWg.toString() : "",
            scrapReason: record.scrapReason || "",

            // 其他信息
            reserveVarchar3: record.reserveVarchar3 || "",
            reserveVarchar4: record.reserveVarchar4 || "",
          };

          // 设置工作班次和班组
          this.workShift = record.workShift || "";
          this.workClass = record.wortkType || "";

          // 设置当前工序
          if (record.processNo) {
            const processIndex = this.processOptions.findIndex(
              (p) => p.processCode === record.processNo
            );
            if (processIndex !== -1) {
              this.currentProcessIndex = processIndex;
              this.currentProcess = this.processOptions[processIndex];
            }
          }

          // 加载炉次投料数据
          if (record.furnaceNo) {
            await this.loadFurnaceData(record.furnaceNo);
          }

          uni.hideLoading();
          uni.showToast({
            title: "数据加载成功",
            icon: "success",
          });

          // 切换到产品下线TAB
          this.activeTab = "product";
        } else {
          uni.hideLoading();
          uni.showToast({
            title: response.msg || "数据加载失败",
            icon: "none",
          });
        }
      } catch (error) {
        uni.hideLoading();
        console.error("加载记录数据失败:", error);
        uni.showToast({
          title: "数据加载失败",
          icon: "none",
        });
      }
    },

    // 加载炉次投料数据
    async loadFurnaceData(furnaceNo) {
      try {
        const params = {
          furnaceNo: furnaceNo,
          batchNo: null,
          pageNum: 1,
          pageSize: 50,
        };

        const response = await LzProdStockRealApi.getLzProdStockRealPage(
          params
        );

        if (response.code === 0 && response.data && response.data.list) {
          this.furnaceTable = response.data.list.map((item) => ({
            furnaceNo: item.furnaceNo || "",
            batchNo: item.batchNo || "",
            processNo: item.processNo || "",
            processName: item.processName || "",
            steelGradeName: item.steelGradeName || "",
            prodSpec: item.prodSpec || "",
            scrapCount: item.scrapCount || 0,
            scrapWg: item.scrapWg || 0,
            inDate: item.inDate || dateHelperApi.getCurrentDate(),
            selected: false, // 初始化选择状态
          }));

          // 如果查询结果只有一行，默认选中该行
          if (this.furnaceTable.length === 1) {
            this.furnaceTable[0].selected = true;
          }
        }
      } catch (error) {
        console.error("加载炉次投料数据失败:", error);
      }
    },

    // 下线成功后刷新表单和炉次列表
    async refreshAfterOffline() {
      try {
        // 清空表单数据（保留一些基础字段）
        this.formData = {
          ...this.formData,
          // 清空与炉次相关的数据
          //furnaceNo: "",
          //furnaceNoDisplay: "",
          reserveVarchar1: "",
          batchNo: "",
          lastBatchNo: "",
          planNo: "",
          steelGradeName: "",
          steelGradeCode: "",
          prodSpec: "",
          standCode: "",
          standNo: "",
          materialCode: "",
          materialName: "",
          // slagSystem: "",
          // slagSystemCode: "",
          // slagRatio: "",
          qaWg: "",
          costWg: "",
          costCount: "",
          qaCount: "",
          scrapCount: "",
          scrapWg: "",
          scrapReason: "",
          reserveVarchar3: "",
          reserveVarchar2: "",
          reserveVarchar1: "",
          reserveVarchar4: "",
          workStaff: "",
          busMemo: "",
        };

        // 清空炉次投料表格
        this.furnaceTable = [];

        // 清空扫码输入
        this.searchForm.searchCode = "";

        // 重新加载计划列表（刷新数据）
        // await this.loadPlanList();

        // 切换到扫码TAB
        // this.activeTab = "scan";

        console.log("下线成功后表单和列表已刷新");
      } catch (error) {
        console.error("刷新表单和列表失败:", error);
      }
    },

    // 修改模式下线
    async handleUpdateOffline() {
      if (!this.editRecordId) {
        uni.showToast({
          title: "未找到修改的记录ID",
          icon: "none",
        });
        return;
      }

      // 校验是否存在炉号
      if (!this.formData.furnaceNo) {
        uni.showToast({
          title: "请先选择炉次号",
          icon: "none",
        });
        return;
      }

      // 校验是否存在批次号
      if (!this.formData.batchNo) {
        uni.showToast({
          title: "请先创建批次号",
          icon: "none",
        });
        return;
      }

      // 校验是否存在计划明细编号
      if (!this.formData.planNo) {
        uni.showToast({
          title: "请先选择计划",
          icon: "none",
        });
        return;
      }

      // 校验是否存在投料重量
      if (!this.formData.costWg || this.formData.costWg === "") {
        uni.showToast({
          title: "请先输入投料重量",
          icon: "none",
        });
        return;
      }

      // 校验投料重量是否为有效数字
      const costWg = parseFloat(this.formData.costWg);
      if (isNaN(costWg) || costWg <= 0) {
        uni.showToast({
          title: "请输入有效的投料重量",
          icon: "none",
        });
        return;
      }

      // 校验是否存在钢锭重量
      if (!this.formData.qaWg || this.formData.qaWg === "") {
        uni.showToast({
          title: "请先输入钢锭重量",
          icon: "none",
        });
        return;
      }

      // 校验钢锭重量是否为有效数字
      const qaWg = parseFloat(this.formData.qaWg);
      if (isNaN(qaWg) || qaWg <= 0) {
        uni.showToast({
          title: "请输入有效的钢锭重量",
          icon: "none",
        });
        return;
      }

      // 校验钢锭重量是否超过投料重量
      if (qaWg > costWg) {
        uni.showToast({
          title: "钢锭重量不能超过投料重量",
          icon: "none",
        });
        return;
      }

      // 校验钢锭支数是否为有效数字
      if (this.formData.qaCount && this.formData.qaCount !== "") {
        const qaCount = parseInt(this.formData.qaCount);
        if (isNaN(qaCount) || qaCount < 0) {
          uni.showToast({
            title: "请输入有效的钢锭支数",
            icon: "none",
          });
          return;
        }
      }

      uni.showModal({
        title: "确认修改下线",
        content: `确定要修改炉次号 ${this.formData.furnaceNo} 的下线数据吗？`,
        success: async (res) => {
          if (res.confirm) {
            try {
              // 准备修改参数
              const updateData = {
                id: this.editRecordId,
                // 基本信息
                furnaceNo: this.formData.furnaceNo,
                reserveVarchar1: this.formData.reserveVarchar1,
                batchNo: this.formData.batchNo,
                processNo: this.currentProcess.processCode,
                processName: this.currentProcess.processName,
                ywDate: this.formData.currentDate,
                workShift: this.workShift,
                wortkType: this.workClass,
                workStaff: this.formData.workStaff,
                busMemo: this.formData.busMemo,

                // 钢种和规格信息
                steelGradeName: this.formData.steelGradeName,
                steelGradeCode: this.formData.steelGradeCode || "",
                prodSpec: this.formData.prodSpec,
                standCode: this.formData.standCode || "",
                standNo: this.formData.standNo || "",
                // 增加物料编码和物料名称参数
                materialCode: this.formData.materialCode || "",
                materialName: this.formData.materialName || "",
                planDetailNo: this.formData.planDetailNo,

                slagSystem: this.formData.slagSystem,
                slagSystemCode: this.formData.slagSystemCode,
                slagRatio: this.formData.slagRatio,

                // 产出信息
                qaWg: parseFloat(this.formData.qaWg) || 0,
                qaCount: parseInt(this.formData.qaCount) || 0,

                // 废品信息
                scrapCount: parseInt(this.formData.scrapCount) || 0,
                scrapWg: parseFloat(this.formData.scrapWg) || 0,
                scrapReason: this.formData.scrapReason,

                // 投料信息（从表格汇总）
                costWg: this.furnaceTable.reduce((sum, item) => {
                  return sum + (parseFloat(item.scrapWg) || 0);
                }, 0),
                costCount: this.furnaceTable.reduce((sum, item) => {
                  return sum + (parseInt(item.scrapCount) || 0);
                }, 0),

                // 当班材料用量
                reserveVarchar3: this.formData.reserveVarchar3,
                reserveVarchar4: this.formData.reserveVarchar4,
              };

              console.log("修改下线参数:", updateData);

              // 调用修改API
              const response = await TcRecordApi.updateTcRecord(updateData);

              if (response.code === 0) {
                uni.showToast({
                  title: "修改下线成功",
                  icon: "success",
                });

                // 退出修改模式
                this.isEditMode = false;
                this.editRecordId = null;

                // 刷新表单和炉次列表
              } else {
                uni.showToast({
                  title: response.msg || "修改下线失败",
                  icon: "none",
                });
              }
            } catch (error) {
              console.error("修改下线处理失败:", error);
              uni.showToast({
                title: "修改下线处理失败，请重试",
                icon: "none",
              });
            }
          }
        },
      });
    },
  },
};
</script>

<style lang="scss">
@import "~@/pages/smart/scss/create.scss";

.custom-checkbox {
  width: 40rpx;
  height: 40rpx;
  border: 2rpx solid #ccc;
  border-radius: 6rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #fff;
  transition: all 0.3s;
  flex-shrink: 0;
  position: relative;

  &.checked {
    border-color: #007aff;
    background-color: #007aff;

    &::after {
      content: "\2713";
      position: absolute;
      color: #fff;
      font-size: 28rpx;
      font-weight: bold;
      line-height: 1;
      top: 50%;
      left: 50%;
      transform: translate(-50%, -50%);
      display: block;
    }
  }
}
</style>
